﻿#include "stlparse.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
using namespace std;

STLParse::STLParse() : data({})
{

}


vector<Triangle> STLParse::getData() const
{
    return this->data;
}

void STLParse::clearData()
{
    if (data.empty()) return;
    this->data.swap(vector<Triangle>(0));
}

bool STLParse::readFile(const QString& fileName)
{
    clearData();
    QFile file(fileName);
    QTextStream in(&file);

    if (!file.open(QFile::ReadOnly | QFile::Text)) {
#ifndef NDEBUG
        qDebug() << fileName << QStringLiteral(":STL文件打开失败");
#endif
        return false;
    }

    Triangle triangle;
    while (!in.atEnd()) {
        QString line = in.readLine();
        vector<QString> words = splitString(line, ' ');
        if (words.size() < 4) continue;

        // 例如：facet normal 0.000000e+000 0.000000e+000 1.000000e+000
        if (words[1] == QStringLiteral("normal")) {
            triangle.normal.x = words[2].toDouble();
            triangle.normal.y = words[3].toDouble();
            triangle.normal.z = words[4].toDouble();
        }
        // 例如：vertex -1.104289e+002 8.257107e+001 6.432000e+002
        if (words[0] == QStringLiteral("vertex")) {
            Point vertex;
            vertex.x = words[1].toDouble();
            vertex.y = words[2].toDouble();
            vertex.z = words[3].toDouble();
            triangle.vertexs.push_back(vertex);
        }
        if (triangle.vertexs.size() == 3) {
            data.push_back(triangle);
            triangle.normal = {0,0,0};
            triangle.vertexs.clear();
        }
    }
    file.close();
    return true;
}


vector<QString> STLParse::splitString(const QString& line, const char& ch) const
{
    if (line.isEmpty()) return {};

    vector<QString> res;
    for (int i = 0; i < line.size(); ++i) {
        QString str;
        while (i < line.size() && line[i] != ch) {
            str += line[i++];
        }
        if (!str.isEmpty()) {
            res.push_back(str);
        }
    }
    return res;
}

